package com.ilink.groundservice.service.impl.Practice;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ilink.groundservice.entity.PO.Practice.AiXPracticeProject;
import com.ilink.groundservice.entity.VO.AiX.AiXPracticeProjectResponse;
import com.ilink.groundservice.mapper.Practice.AiXPracticeProjectMapper;
import com.ilink.groundservice.mapper.AiX.AiXTagConnectMapper;
import com.ilink.groundservice.service.Practice.AiXPracticeProjectService;
import com.ilink.ilinkapi.dto.ground.AiX.AiXPracticeProjectFilterRequest;
import com.ilink.ilinkapi.dto.ground.AiX.AiXPracticeProjectInsertRequest;
import com.ilink.ilinkapi.dto.ground.AiX.AiXPracticeProjectUpdateRequest;
import com.ilink.ilinkcommon.exception.BizIllegalException;
import com.ilink.ilinkcommon.utils.BeanUtils;
import com.ilink.ilinkcommon.service.oss.OssService;
import com.ilink.ilinkcommon.utils.SnowflakeIdGenerator;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class AiXPracticeProjectServiceImpl implements AiXPracticeProjectService {

    private final AiXPracticeProjectMapper practiceProjectMapper;
    private final OssService ossService;
    private final AiXTagConnectMapper aiXTagConnectMapper;

    @Override
    public IPage<AiXPracticeProjectResponse> getPracticeProjectList(AiXPracticeProjectFilterRequest request) {
        Page<AiXPracticeProjectResponse> page = new Page<>(request.getPage(), request.getSize());
        // 如果有标签筛选，使用标签筛选方法；否则使用原有方法
        IPage<AiXPracticeProjectResponse> result;
        if (request.getTag() != null && !request.getTag().trim().isEmpty()) {
            result = practiceProjectMapper.selectPracticeProjectPageByTag(page, request);
        } else {
            result = practiceProjectMapper.selectPracticeProjectPage(page, request);
        }
        
        // 为每个实训项目设置标签列表
        result.getRecords().forEach(project -> {
            List<String> tags = practiceProjectMapper.selectPracticeProjectTags(project.getProjectId());
            project.setTags(tags);
        });
        
        return result;
    }

    @Override
    public AiXPracticeProjectResponse getPracticeProjectById(Long projectId) {
        if (projectId == null) {
            throw new BizIllegalException("实践项目ID不能为空");
        }
        
        AiXPracticeProjectResponse response = practiceProjectMapper.selectPracticeProjectById(projectId);
        if (response == null) {
            throw new BizIllegalException("实践项目不存在");
        }
        
        // 设置标签列表
        List<String> tags = practiceProjectMapper.selectPracticeProjectTags(projectId);
        response.setTags(tags);
        
        return response;
    }

    @Override
    @Transactional
    public Long insertPracticeProject(AiXPracticeProjectInsertRequest request) {
        if (request == null) {
            throw new BizIllegalException("请求参数不能为空");
        }
        
        AiXPracticeProject practiceProject = BeanUtils.copyBean(request, AiXPracticeProject.class);
        
        // 使用雪花算法生成ID
        SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(7, 1);
        practiceProject.setProjectId(idGenerator.nextId());
        
        practiceProject.setCreatedAt(LocalDateTime.now());
        practiceProject.setUpdatedAt(LocalDateTime.now());
        
        // 处理封面图片上传
        if (request.getProjectCover() != null && !request.getProjectCover().isEmpty()) {
            String coverUrl = ossService.uploadFileAndGetUrl(request.getProjectCover(), "study-square-migrate", "practice-project/cover_" + System.currentTimeMillis() + "_" + request.getProjectCover().getOriginalFilename());
            practiceProject.setProjectCover(coverUrl);
        }
        
        int result = practiceProjectMapper.insert(practiceProject);
        if (result <= 0) {
            throw new BizIllegalException("实践项目创建失败");
        }
        
        return practiceProject.getProjectId();
    }

    @Override
    @Transactional
    public void updatePracticeProject(AiXPracticeProjectUpdateRequest request) {
        if (request == null || request.getProjectId() == null) {
            throw new BizIllegalException("请求参数不能为空");
        }
        
        AiXPracticeProject existingProject = practiceProjectMapper.selectById(request.getProjectId());
        if (existingProject == null) {
            throw new BizIllegalException("实践项目不存在");
        }
        
        AiXPracticeProject practiceProject = BeanUtils.copyBean(request, AiXPracticeProject.class);
        practiceProject.setUpdatedAt(LocalDateTime.now());
        
        // 处理封面图片上传
        if (request.getProjectCover() != null && !request.getProjectCover().isEmpty()) {
            String coverUrl = ossService.uploadFileAndGetUrl(request.getProjectCover(), "study-square-migrate", "practice-project/cover_" + System.currentTimeMillis() + "_" + request.getProjectCover().getOriginalFilename());
            practiceProject.setProjectCover(coverUrl);
        }
        
        int result = practiceProjectMapper.updateById(practiceProject);
        if (result <= 0) {
            throw new BizIllegalException("实践项目更新失败");
        }
    }

    @Override
    @Transactional
    public void deletePracticeProject(Long projectId) {
        if (projectId == null) {
            throw new BizIllegalException("实践项目ID不能为空");
        }
        
        AiXPracticeProject practiceProject = practiceProjectMapper.selectById(projectId);
        if (practiceProject == null) {
            throw new BizIllegalException("实践项目不存在");
        }
        
        int result = practiceProjectMapper.deleteById(projectId);
        if (result <= 0) {
            throw new BizIllegalException("实践项目删除失败");
        }
    }

    @Override
    @Transactional
    public void updatePracticeProjectCover(MultipartFile file, Long projectId) {
        if (file == null || file.isEmpty()) {
            throw new BizIllegalException("封面文件不能为空");
        }
        if (projectId == null) {
            throw new BizIllegalException("实践项目ID不能为空");
        }
        
        AiXPracticeProject practiceProject = practiceProjectMapper.selectById(projectId);
        if (practiceProject == null) {
            throw new BizIllegalException("实践项目不存在");
        }
        
        String coverUrl = ossService.uploadFileAndGetUrl(file, "study-square-migrate", "practice-project/cover_" + System.currentTimeMillis() + "_" + file.getOriginalFilename());
        practiceProject.setProjectCover(coverUrl);
        practiceProject.setUpdatedAt(LocalDateTime.now());
        
        int result = practiceProjectMapper.updateById(practiceProject);
        if (result <= 0) {
            throw new BizIllegalException("实践项目封面更新失败");
        }
    }

    @Override
    public List<AiXPracticeProjectResponse> getPopularPracticeProjects(Integer limit) {
        if (limit == null || limit <= 0) {
            limit = 10;
        }
        List<AiXPracticeProjectResponse> results = practiceProjectMapper.selectPopularPracticeProjects(limit);
        
        // 为每个实训项目设置标签列表
        results.forEach(project -> {
            List<String> tags = practiceProjectMapper.selectPracticeProjectTags(project.getProjectId());
            project.setTags(tags);
        });
        
        return results;
    }

    @Override
    public List<String> getPracticeProjectTags(Long areaId) {
        return aiXTagConnectMapper.getPracticeProjectTags(areaId, 8);
    }

    @Override
    public List<String> getAllPracticeProjectTags(Long areaId) {
        return aiXTagConnectMapper.getAllPracticeProjectTags(areaId);
    }
} 